package hong.jun.springsecurity;

import hong.jun.doamin.Permission;
import hong.jun.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.List;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private PermissionMapper permissionMapper;

    /*模拟jdbc查到的数据*/
   /* @Bean
    public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withUsername("zs").password("123").authorities("admin").build());
        return inMemoryUserDetailsManager;
    }*/
    //Security会处理比密码 需要提供是否加密和加密类型
    @Bean
    public PasswordEncoder passwordEncoder() {
        //return NoOpPasswordEncoder.getInstance();//密码编码器：未加密
        return new BCryptPasswordEncoder();   //密码编码器：SpringSecurity内部提供的编码器 ，加密结果在改变且能比对
    }

    //授权规则配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //查询系统的所有权限列表
        List<Permission> permissions = permissionMapper.loadall();

        //把权限设置给security
        for (Permission permission : permissions) {
            http.authorizeRequests().antMatchers(permission.getUrl()).hasAuthority(permission.getName());
        }
        http.authorizeRequests()                                //授权配置
                .antMatchers("/login", "/login.html").permitAll()  //登录请求和页面路径放行
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                              //允许表单登录
                .successForwardUrl("/loginSuccess")             // 设置登陆成功页
                .loginPage("/login.html")                       //登录跳转页面路径
                .loginProcessingUrl("/login")                   //登录处理地址(必须)
                .and().logout().permitAll()                    //登出路径放行 就是注销
                .and().csrf().disable();                        //关闭跨域伪造检查
    }
}
